All files / web/src/app/api/postcards/[postcardId]/retry route.ts

0% Statements 0/50
0% Branches 0/1
0% Functions 0/1
0% Lines 0/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51                                                                                                     
import { NextResponse, type NextRequest } from 'next/server'
import { withAuth, type AuthenticatedContext } from '@/lib/auth/withAuth'
import { getUserId } from '@/lib/viewer'
import { db } from '@/db'
import * as schema from '@/db/schema'
import { eq, and } from 'drizzle-orm'
import { startPostcardGenerate } from '@/lib/tasks/postcard-generate'

/** POST /api/postcards/:postcardId/retry — retry a failed postcard generation */
export const POST = withAuth(async (_request: NextRequest, context: AuthenticatedContext) => {
  const userId = await getUserId()
  const params = await context.params
  const postcardId = params.postcardId as string

  const [postcard] = await db
    .select()
    .from(schema.numberLinePostcards)
    .where(
      and(
        eq(schema.numberLinePostcards.id, postcardId),
        eq(schema.numberLinePostcards.userId, userId)
      )
    )
    .limit(1)

  if (!postcard) {
    return NextResponse.json({ error: 'Postcard not found' }, { status: 404 })
  }

  if (postcard.status !== 'failed' && postcard.status !== 'pending') {
    return NextResponse.json(
      { error: `Cannot retry postcard with status "${postcard.status}"` },
      { status: 400 }
    )
  }

  await db
    .update(schema.numberLinePostcards)
    .set({ status: 'pending', updatedAt: new Date() })
    .where(eq(schema.numberLinePostcards.id, postcardId))

  const taskId = await startPostcardGenerate({ postcardId, userId })

  await db
    .update(schema.numberLinePostcards)
    .set({ taskId })
    .where(eq(schema.numberLinePostcards.id, postcardId))

  return NextResponse.json({ postcardId, taskId })
})